package com.itheima.itcasthealth.filter;

import com.itheima.itcasthealth.entiry.Member;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;


        String uri = req.getRequestURI();

        String[] urls = {
                "/validateCode/send4Login.do",
                "/member/login.do",
                "/css/**",
                "/fonts/**",
                "/img/**",
                "/pages/login.html",
                "/plugins/**",
        };

        for (String url : urls) {
            boolean match = antPathMatcher.match(url, uri);
            if (match){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }

        HttpSession session = req.getSession();
        Member member = (Member) session.getAttribute("user");

        if (member == null){
            resp.sendRedirect("/pages/login.html");
            return;
        }

        filterChain.doFilter(servletRequest,servletResponse);

    }
}
